import { Form, Input, Button, Drawer, Collapse, message, Select, Divider, Space, Row, Col, Popconfirm } from 'antd'
import { fetchArticleAdd, fetchBackend, fetchTags } from '@/api'
import { IsBrowser } from '@/components/IsBrowser'
import AppUpload from '@/components/AppUpload'
import Bytemd from '@/components/Bytemd'
import { useRouter } from 'next/router'
import { useSetState } from 'ahooks'
import { useEffect, useState } from 'react'
import { marked } from 'marked'
import { Method } from 'axios'
import Image from 'next/image'
import { notice } from '@/utils'
import AppConfig from '@/config'
import Head from 'next/head'

const { TextArea } = Input
const { Option } = Select
const { Panel } = Collapse

const { title } = AppConfig

type PageProps = {
  backendList: any
  tagList: any
}

export default function Edit({ backendList, tagList }: PageProps) {
  const router = useRouter()
  const [form] = Form.useForm()
  const [data, setData] = useState<any>({})
  const { validateFields } = form
  const { id: article_id, nav_id } = router.query
  const [state, setState] = useSetState({ content: '', md: '', is_top: 2, status: 0, tags: [], tags_id: 0, nav: 1 })
  const [open, setOpen] = useState(false)
  const [editorMd, seteditorMd] = useState<string>('')
  const isEdit = !!article_id
  const API_URL = process.env.NEXT_PUBLIC_API_URL
  // 默认值
  const defaultValues = {
    isTop: 0, // 1 置顶, 0 不置顶
    status: 1, // 状态
    userId: 1, // 作者
  }
  // 上传配置
  const uploadConfig = {
    maxCount: 1,
    accept: '.jpg,.jpeg,.png',
    action: `${API_URL}/api/file/upload`,
    showUploadList: false,
  }

  useEffect(() => {
    seteditorMd('')
    nav_id && setState({ nav: +nav_id })
  }, [])

  // 处理成功
  const handleSuccess = (txt: string) => {
    notice({ description: txt })

    setTimeout(() => {
      setOpen(false)
      isEdit ? router.push('/admin') : window.location.reload()
    }, 1000)
  }

  // 新增
  const createData = (params: any, txt: string) => {
    fetchArticleAdd(params).then(() => {
      handleSuccess(txt)
    })
  }

  // MD改变
  const onMdEditorChange = (value: string) => {
    setState({ md: value })
  }

  const onOpen = () => {
    setOpen(true)
  }

  // 提交接口
  const handleFinish = (params: any) => {
    let method: Method = 'post'
    let txt = '发布成功'

    if (isEdit) {
      method = 'patch'
      txt = '修改成功'
    }

    if (!params.title) {
      message.error('请输入标题')
      return
    }

    const fParams = { type: method, params }
    createData(fParams, txt)
  }

  // 处理关闭抽屉菜单
  const handleClose = () => {
    setOpen(false)
  }

  // 业务处理
  const handleModelForm = (modelForm: any) => {
    modelForm.tags = tagList.filter((tag: any) => modelForm.tagId === tag.id)
    modelForm.backend = backendList.filter((back: any) => modelForm.backend === back.id)

    return modelForm
  }

  // 保存
  const onSave = () => {
    validateFields().then(async (values: any) => {
      Object.assign(values, defaultValues, { ...data })

      if (isEdit) {
        values.id = +article_id
      }

      if (!values.github && !values.gitee) {
        message.error('请输入Github或Gitee仓库地址')
        return
      }

      const { md, content } = state
      md && (values.md = md)
      values.content = md ? marked(md, { sanitize: true }) : content

      if (!values.content) {
        message.error('请输入内容')
        return
      }

      handleFinish(handleModelForm(values))
    }).finally(() => {})
  }

  // 取消
  const onCancel = () => {
    handleClose()
  }

  // 上传成功
  const onUploadSuccess = ({ url }: { url: any }) => {
    const coverUrl = `${API_URL}/${url.path}`

    setData({ coverUrl })
  }

  // 上传失败
  const onUploadFail = () => { }

  const onChangeNav = (nav: number) => {
    setState({ nav })
  }

  // 删除图片
  const onDelImg = (url: string) => {
    console.log('url', url)
    setData({ coverUrl: '' })
  }

  // 上传前
  const beforeUpload = (
    <AppUpload title="上传图片" config={uploadConfig} onSuccess={onUploadSuccess} onFail={onUploadFail} />
  )

  // 上传后
  const afterUpload = (
    <div className="upload-image">
      <Space direction="vertical" size={15} className="thumb-space">
        <Image loader={() => data.coverUrl} src={data.coverUrl} alt="上传图片" unoptimized className="mr-3" width={150} height={150} />
        <Popconfirm title="确定要删除吗?" onConfirm={() => onDelImg(data.coverUrl)}>
          <Button type="default" danger size="small">删除</Button>
        </Popconfirm>
      </Space>
    </div>
  )

  // 标签，只有在管理模板时出现
  const tagElement = (
    <Form.Item name="tagId" label="UI组件">
      <Select placeholder="请选择UI组件" style={{ width: '100%' }}>
        {tagList?.length > 0 && tagList.map((tag: any) => {
          return (
            <Option value={tag.id} key={tag.id}>{tag.tagName}</Option>
          )
        })}
      </Select>
    </Form.Item>
  )

  // 初始化数据
  const initialValues = {
    navId: +(nav_id || 1),
    version: 18,
    tagId: 9,
  }

  return (
    <div className="app-edit-container">
      <Head>
        <title>{`提交 - ${title}`}</title>
      </Head>
      <div className="app-page-edit">
        <Form
          className="app-edit-form"
          form={form}
          layout="vertical"
          name="basic"
          preserve={false}
          requiredMark={false}
          initialValues={initialValues}
          autoComplete="off"
        >
          <div className="app-md-header">
            <div className="app-md-title">
              <Form.Item name="title" rules={[{ required: true, message: '请输入标题' }, { whitespace: true, message: '标题不能为空' }]} className="app-search-title-form relative">
                <Input placeholder="请输入标题" />
              </Form.Item>
            </div>
            <div className="app-md-action">
              <Button type="primary" className="app-md-btn" onClick={onOpen}>发布</Button>
            </div>
          </div>
          <div className="app-md-editor markdown-body">
            <IsBrowser>
              <Bytemd content={editorMd} onMdEditorChange={onMdEditorChange} />
            </IsBrowser>
          </div>
          <Drawer width={575} className="app-editor-drawer" placement="right" closable onClose={() => handleClose()} open={open}>
            <Collapse defaultActiveKey={['1', '2', '3', '4']} ghost className="app-editor-collapse" expandIconPosition="end">
              <Panel header="版本" key="1">
                <Row gutter={15} className="app-row-version">
                  <Col span={10}>
                    <Form.Item name="version">
                      <Select placeholder="请选择版本" style={{ width: '100%' }}>
                        <Option value={18}>React18</Option>
                        <Option value={17}>React17</Option>
                        <Option value={16}>&lt;=React16</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={14}>
                    <Form.Item label="后台语言" name="backend">
                      <Select placeholder="请选择后台语言" style={{ width: '100%' }}>
                        {backendList?.length > 0 && backendList.map((bank: any) => {
                          return (
                            <Option value={bank.id} key={bank.id}>{bank.backendName}</Option>
                          )
                        })}
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              </Panel>

              <Panel header="文章信息" key="2">
                <Row gutter={15} className="mb-5">
                  <Col span={12}>
                    <Form.Item label="类别" labelCol={{ span: 6 }} name="navId" rules={[{ required: true, message: '请选择类别' }]}>
                      <Select placeholder="请选择类别" onChange={onChangeNav}>
                        <Option value={1}>Admin</Option>
                        <Option value={2}>UI组件库</Option>
                        <Option value={3}>Hooks</Option>
                        <Option value={4}>CLI</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    {state.nav === 1 && tagElement}
                  </Col>
                </Row>
                <Form.Item labelCol={{ span: 3 }} label="Github" name="github">
                  <Input placeholder="请输入Github" autoComplete="off" />
                </Form.Item>
                <Form.Item labelCol={{ span: 3 }} label="Gitee" name="gitee">
                  <Input placeholder="请输入Gitee" autoComplete="off" />
                </Form.Item>
                <Form.Item labelCol={{ span: 3 }} label="主页" name="homepage">
                  <Input placeholder="请输入主页" autoComplete="off" />
                </Form.Item>
                <Form.Item labelCol={{ span: 3 }} label="作者" name="author" rules={[{ required: true, message: '请输入作者' }]}>
                  <Input placeholder="请输入作者" maxLength={30} autoComplete="off" />
                </Form.Item>
              </Panel>

              <Panel header="简介" key="3">
                <Form.Item name="summary" rules={[{ required: true, message: '请输入简介' }]}>
                  <TextArea placeholder="请输入简介" autoComplete="off" autoSize={{ minRows: 2, maxRows: 6 }} showCount maxLength={200} />
                </Form.Item>
              </Panel>

              <Panel header="封面图" key="4">
                {data.coverUrl ? afterUpload : beforeUpload}
                <div className="mt-3 text-xs text-gray-400 font-mono">支持jpg、png、jpeg大小 2M 以内的图片</div>
              </Panel>
            </Collapse>
            <div className="app-editor-popup px-4">
              <Divider />
              <div className="app-editor-popup-footer">
                <Space size={15}>
                  <Button onClick={onCancel}>取消</Button>
                  <Button type="primary" onClick={onSave}>提交</Button>
                </Space>
              </div>
            </div>
          </Drawer>
        </Form>
      </div>
    </div>
  )
}

export async function getServerSideProps() {
  const { rows: backendList } = await fetchBackend({ params: { type: 1 } })
  const { rows: tagList } = await fetchTags({ params: { type: 2 } })

  return { props: { backendList, tagList } }
}
